#include "pic.h"



int show_jpeg_file (LcdDev *lcd , char * filename,int start_pix_x,int start_pix_y)
{

 	int	tmp_height=0;
 	int	tmp_width=0;
 	int tmp_count=0;
 	int tmp_pix=0;
 	// int tmp_width=0;
	//解码结构
	struct jpeg_decompress_struct cinfo;
	//错误处理结构
	struct jpeg_error_mgr jerr;
	/* More stuff */
	FILE * infile;		/* source file */
	//保存一行像素
	//unsigned char **buffer;
	JSAMPARRAY buffer;		/* Output row buffer */
	int row_stride;		/* physical row width in output buffer */

	//打开要解码的图片文件
	if ((infile = fopen(filename, "rb")) == NULL) {
		fprintf(stderr, "can't open %s\n", filename);
		return 0;
	}

	/* Step 1: allocate and initialize JPEG decompression object */
	cinfo.err = jpeg_std_error(&jerr);
	//初始解码对象
	jpeg_create_decompress(&cinfo);
	/* Step 2: specify data source (eg, a file) */
	//把图片加载到解码对象中
	jpeg_stdio_src(&cinfo, infile);
	/* Step 3: read file parameters with jpeg_read_header() */
	//读取文件头
	(void) jpeg_read_header(&cinfo, TRUE);
	/* Step 4: set parameters for decompression */

	/* Step 5: Start decompressor */
	//开始解码
	(void) jpeg_start_decompress(&cinfo);
	//计算解码后一行像素有多少字节（一行宽度*一个像素占的字节数）
	row_stride = cinfo.output_width * cinfo.output_components;
	//分配空间来存储解码后的数据
	buffer = (*cinfo.mem->alloc_sarray)
		((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
	/* Step 6: while (scan lines remain to be read) */
	/*	 jpeg_read_scanlines(...); */
	//cinfo.output_scanline 当前解码那一行（当今行<图片总共行数）
	if (cinfo.output_height>=480){
		tmp_height=480;
	}else{
		tmp_height=cinfo.output_height;
	}
	if (cinfo.output_width>=800){
		tmp_width=800;
	}else{
		tmp_width=cinfo.output_width;
	}
	printf("open : %s\n",filename );
	while (cinfo.output_scanline < cinfo.output_height) {
	//output_scanline是从1开始，所以需要减1
	//解一行数放在buffer中(buffer中的数据是RGBRGB.....)
	(void) jpeg_read_scanlines(&cinfo, buffer, 1);
	//把buffer中的数据绘制lcd上
	if(tmp_count<tmp_height){
		unsigned char *p = buffer[0];
		int i=0; 
		for(i=0; i<tmp_width; i++){
		 	tmp_pix=*(p+2);
		 	tmp_pix= tmp_pix|*(p+1)<<8|*p<<16;
		 	*(lcd->p-1+i+start_pix_x/*开始像素x轴*/+(start_pix_y/*开始像素y轴*/+cinfo.output_scanline-1)*lcd->wscreen)=tmp_pix;
			p+=3;
		}
	}
	tmp_count++;
	}
	/* Step 7: Finish decompression */
	(void) jpeg_finish_decompress(&cinfo);
	/* Step 8: Release JPEG decompression object */
	jpeg_destroy_decompress(&cinfo);
	fclose(infile);
	return 1;
}